package com.fourhats.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.fourhats.dao.ItemDAO;
import com.fourhats.dao.PlaceDAO;
import com.fourhats.dao.PriceDAO;
import com.fourhats.model.Item;
import com.fourhats.model.Place;
import com.fourhats.model.Price;
import com.fourhats.services.PriceService;
import com.fourhats.services.dto.PriceDto;

public class PriceServiceImpl implements PriceService {

	@Autowired
	private PriceDAO priceDAO;
	
	@Autowired
	private ItemDAO itemDAO;
	
	@Autowired
	private PlaceDAO placeDAO;
	
	@Autowired
	private Mapper mapper;
	
	@Override
	public List<PriceDto> getEnabledPricesByItemAndPlace(long itemId, List<Long> placeIds) {
		List<Price> prices = priceDAO.getEnabledPricesByItemAndPlace(itemId, placeIds);
		List<PriceDto> dtos = new ArrayList<PriceDto>();
		for(Price p : prices) {
			dtos.add(mapper.map(p, PriceDto.class));
		}
		
		return dtos;
	}

	@Override
	public void addPrice(long itemId, long placeId, Double value) {
		Item item = itemDAO.getById(itemId);
		Place place = placeDAO.getById(placeId);
		Price newPrice = new Price(item, place, value);
		
		List<Price> oldPrices = priceDAO.getHistoricalPricesByItemAndPlace(itemId, placeId);
		for (Price price : oldPrices) {
			price.setEnable(false);
			priceDAO.update(price);
		}
		
		priceDAO.add(newPrice);
	}
}
